const {
  formatDate,
  range,
  accAdd,
} = require('../../utils/util.js')
const {
  API_PREFIX
} = require('../../utils/config.js')

const days = {
  0: '周日',
  1: '周一',
  2: '周二',
  3: '周三',
  4: '周四',
  5: '周五',
  6: '周六',
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    nickName: '', // 用户昵称
    avatarUrl: '', // 用户头像
    userId: '', // 用户id
    cashbookId: '', // 记账本id
    cashbookName: '', // 记账本名称

    monthTotalIncome: '', // 当月累计收入
    monthTotalPay: '', // 当月累计支出
    detailList: [], // 当月流水账明细

    multiArray: [
      range(2018, 2030),
      range(1, 12),
    ],
    currentDate: [], // 当前日期

    slideButtons: [{ // 删除按钮
      text: '删除',
      type: 'warn',
    }],

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(e) {
    this.setData({
      userId: ''
    })
    var that = this

    wx.login({
      success(res) {
        if (res.code) {
          wx.request({
            url: `${API_PREFIX}/user`,
            method: 'GET',
            data: {
              code: res.code
            },
            success: function(res) {
              if (res.data && res.data.data) {
                const {
                  avatarUrl,
                  nickname,
                  userId,
                  cashbooks
                } = res.data.data

                that.setData({
                  userId,
                  avatarUrl,
                  nickName: nickname,
                  cashbookId: cashbooks[0].id,
                  cashbookName: cashbooks[0].name,
                })

                wx.setStorageSync('userId', userId)
                that.handleGetDetails()
              }
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })

    this.handleInitDate()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function(e) {
    if (!this.data.userId) {
      return
    }

    this.handleGetDetails()
  },

  /**
   * 初始化当前年月日
   */
  handleInitDate: function() {
    const today = new Date()
    const year = today.getFullYear()
    const month = today.getMonth() + 1

    const {
      multiArray
    } = this.data
    const years = multiArray[0]
    const months = multiArray[1]

    const yearIndex = years.findIndex(item => item == year)
    const monthIndex = months.findIndex(item => item == month)
    this.setData({
      currentDate: [yearIndex, monthIndex]
    })
  },

  /**
   * 查询账本明细记录
   */
  handleGetDetails: function(year = '', month = '') {
    var that = this
    const {
      cashbookId
    } = this.data
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: `${API_PREFIX}/details`,
      data: {
        cashbookId,
        year,
        month,
      },
      method: 'GET',
      success: function(res) {
        // 时间格式化
        let serveDatail = res.data.data
        serveDatail = serveDatail.map(item => {
          item.create_date = formatDate(new Date(item.create_date))
          return item
        })

        // 根据日期进行一次分类
        const detailInfo = {}
        serveDatail.forEach(item => {
          const date = item.create_date
          if (!detailInfo[date]) {
            detailInfo[date] = []
          }
          detailInfo[date].push(item)
        })

        // 修改明细列表数据结构
        const list = []
        Object.keys(detailInfo).forEach(key => {
          const value = detailInfo[key]
          const o = Object.create(null)

          o.date = key // 日期
          o.day = days[new Date(key).getDay()] // 星期
          o.details = [] // 当天详细记录
          o.totalIncome = 0 // 当前总收入
          o.totalPay = 0 // 当天总支出

          value.forEach(item => {
            if (item.amt_type < 0) {
              o.totalPay = accAdd(o.totalPay, item.amt).toFixed(2)
            } else {
              o.totalIncome = accAdd(o.totalIncome, item.amt).toFixed(2)
            }
            item.amt = (item.amt * item.amt_type).toFixed(2)
            delete item.createTime
            delete item.amt_type
            o.details.push(item)
          })

          list.push(o)
        })

        // 计算当月累计总收入，当月累计总支出
        let monthTotalIncome = 0
        let monthTotalPay = 0
        list.forEach(item => {
          monthTotalIncome = accAdd(monthTotalIncome, item.totalIncome).toFixed(2)
          monthTotalPay = accAdd(monthTotalPay, item.totalPay).toFixed(2)
        })

        that.setData({
          detailList: list,
          monthTotalIncome,
          monthTotalPay,
        })

        wx.hideLoading()
      },
      fail: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 删除明细记录
   */
  handleDeteleDetail: function(e) {
    const {
      id
    } = e.currentTarget.dataset
    const that = this
    wx.showModal({
      title: '删除提示',
      content: '确定删除？',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: `${API_PREFIX}/detail/${id}`,
            method: 'DELETE',
            success: function(res) {
              wx.showToast({
                title: '删除成功',
              })
              that.handleGetDetails()
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })


  },

  /**
   * 跳转到明细记录详情页面
   */
  handleShowDetail: function(event) {
    const {
      detail
    } = event.currentTarget.dataset
    wx.navigateTo({
      url: `../detail/detail?id=${detail.id}&createDate=${detail.create_date}`
    })
  },

  /**
   * 跳转到记账页面
   */
  handleGoChargePage: function() {
    const {
      userId,
      cashbookId,
      avatarUrl
    } = this.data
    wx.navigateTo({
      url: `../charge/index?userId=${userId}&cashbookId=${cashbookId}&avatarUrl=${avatarUrl}`
    })
  },

  /**
   * 选择年、月
   */
  handleChangeDate: function(e) {
    const currentDate = e.detail.value
    this.setData({
      currentDate
    })

    const {
      multiArray
    } = this.data
    const year = multiArray[0][currentDate[0]]
    const month = multiArray[1][currentDate[1]]
    this.handleGetDetails(year, month)
  },

  /**
   * 获取用户微信信息
   */
  onGotUserInfo: function(e) {
    const {
      nickName,
      avataruRL
    } = e.detail.userInfo
    this.setData({
      nickName,
      avatarUrl,
    })

    // 保存用户头像和昵称
    const {
      userId
    } = this.data
    wx.request({
      url: `${API_PREFIX}/user`,
      method: 'PUT',
      data: {
        id: userId,
        nickname: nickName,
        avatarUrl,
      },
      success: function(res) {}
    })
  },
  //跳转到图表页面
  handleChangeChartPage: function () {
    wx.navigateTo({
      url: '../chart/index',
    })
  }
})